package org.example.test5.service.serviceImpl;

import org.example.test5.mapper.CardMapper;
import org.example.test5.mapper.UserMapper;
import org.example.test5.model.Card;
import org.example.test5.service.UserService;
import org.example.test5.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CardMapper cardMapper;

    @Override
    public boolean login(String uname, String upwd) {
        User user = userMapper.findUserByName(uname);
        return user != null && user.getUpwd().equals(upwd); // 如果用户存在且密码匹配，登录成功
    }

    // 注册
    @Transactional
    @Override
    public boolean register(User user) {
        // 检查用户是否已存在
        User existingUser = userMapper.findUserByName(user.getUname());
        if (existingUser != null) {
            return false;  // 用户已存在
        }

        // 插入用户并自动生成 id
        userMapper.insertUser(user);

        // 确保插入后 user 对象的 id 被正确赋值
        int id = user.getId();
        if (id != 0) {
            Card card = new Card();
            card.setName(user.getUname());
            card.setAddress("暂无");
            card.setCompany("暂无");
            card.setEmail("暂无");
            card.setLogoName("暂无");
            card.setPost("暂无");
            card.setTelephone("暂无");
            card.setAddress("暂无");
            card.setUserId(id);  // 使用插入后的 id
            cardMapper.insertCard(card);
        }

        return true;
    }

}